<template>
  <form class="article-infos-choice-wrapper" @submit.prevent>

    <div class="cover-wrapper wrapper">
      <h2 class="w1">封面:</h2>
      <cover-upload class="cover-upload w2"
      ref="coverUpload"
      ></cover-upload>
    </div>

    <div class="digest-wrapper wrapper">
      <h2 class="w1">摘要:</h2>
      <text-area class="digest-input w2"
      v-model:value="digest"
      ></text-area>
    </div>

    <div class="type-wrapper wrapper">
      <h2 class="w1">分类:</h2>
      <type-list class="type-list w2"
      :types="typeNames" v-model:typeSelect="typeSelect"></type-list>
    </div>

    <div class="tag-wrapper wrapper">
      <h2 class="w1">文章标签:</h2>
      <tag-list class="tag-list w2"
      :tags="pubTags"
      @addTag="addTag"
      @delTag="delTag"
      ></tag-list>
    </div>

    <div class="original-wrapper wrapper">
      <h2 class="w1">是否原创</h2>
      <div class="w2">
        <input type="radio" value="origin" name="original" id="original"
        v-model="original">
        <label for="original">原创</label>
        <input type="radio" value="reprint" name="original" id="reprint"
        v-model="original">
        <label for="reprint">转载</label>
      </div>
    </div>

    <div class="submit-wrapper">
      <button class="submit" @click.prevent="pubArticle" ref="submitBtn">发布</button>
      <button class="store" @click.prevent="storeArticle" ref="storeBtn">存草稿</button>
    </div>
  </form>
</template>

<script>
import { mapState } from 'vuex';
import { confirm } from '@/utils/alert.js';

import TextArea from '@c/utils/Input/TextArea.vue';
import CoverUpload from '../utils/CoverUpload.vue';
import TypeList from '../utils/TypeList.vue';
import TagList from '../utils/TagList.vue';

  export default {
    components: {
      TextArea,
      CoverUpload,
      TypeList,
      TagList
    },
    data() {
      return {
        typeSelect: [],
        original: 'origin',
        digest: '',
        pubTags: [],
        cover: null,
      }
    },
    computed: {
      ...mapState(['tagNames', 'typeNames']),
      draftId() {
        let id = parseInt(this.$route.query.draftId);
        if(isNaN(id)) id = undefined;
        return id;
      }
    },
    methods: {
      addTag(tag) {
        if(this.pubTags.includes(tag)) {
          this.$alert('标签已经添加！');
        } else {
          this.pubTags.push(tag);
        }
      },

      delTag(idx) {
        this.pubTags.splice(idx, 1);
      },

      pubArticleWithData(data) {
        this.$refs.submitBtn.disabled = true;
        this.$confirm("确认发布?").then(flag => {
          if(flag) {
            this.$parent.pubArticle(data).then(res => {
              if(res.data.success) {
                this.$alert('发布成功!').then(() => {
                  // this.$open('/');
                })
              } else {
                this.$alert({
                  type: 'error',
                  content: '发布失败，请重试'
                });
                this.$refs.submitBtn.disabled = false;
              }
            }).catch(error => {
              this.$alert({
                type: 'error',
                content: '发布失败，请重试'
              });
              this.$refs.submitBtn.disabled = false;
            });
          } else {
            this.$refs.submitBtn.disabled = false;
          }
        })
      },
      pubArticle() {
        if(!this.$refs.coverUpload.checkCover()) {
          this.$alert({
            type: 'error',
            content: '请上传封面'
          });
          return;
        } else if(this.typeSelect.every(e => !e)) {
          this.$alert({
            type: 'error',
            content: '请选择分类'
          });
          return;
        }
        this.cover = this.$refs.coverUpload.getCover();
        if(this.cover) {
          this.$compressImage(this.cover).then(res => {
            this.cover = res;
            let data = {
              cover: res,
              tag: this.pubTags.join(','),
              type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
              original: this.original === 'origin' ? 1 : 0,
              digest: this.digest
            };
            this.pubArticleWithData(data);
          })
        } else {
          let data = {
            tag: this.pubTags.join(','),
            type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
            original: this.original === 'origin' ? 1 : 0,
            digest: this.digest
          };
          this.pubArticleWithData(data);
        }
      },

      storeArticleWithData(data) {
        if(this.draftId) {
          confirm("是否覆盖原草稿？").then(flag => {
            if(flag) {
              data.draft_id = this.draftId;
              this.$parent.updateArticleDraft(data).then(res => {
                if(res.data.success) {
                  this.$alert("保存成功");
                } else {
                  this.$alert({
                    type: 'error',
                    content: '保存失败'
                  });
                }
              }).catch(error => {
                this.$alert({
                  type: 'error',
                  content: '保存失败'
                });
              })
            }
            else {
              this.$parent.storeArticle(data).then(res => {
                if(res.data.success) {
                  this.$alert("保存成功");
                } else {
                  this.$alert({
                    type: 'error',
                    content: '保存失败'
                  });
                }
              }).catch(error => {
                this.$alert({
                  type: 'error',
                  content: '保存失败'
                });
              })
            }
          });
        } else {
          this.$parent.storeArticle(data).then(res => {
            if(res.data.success) {
              this.$alert("保存成功");
            } else {
              this.$alert({
                type: 'error',
                content: '保存失败'
              });
            }
          }).catch(error => {
            this.$alert({
              type: 'error',
              content: '保存失败'
            });
          })
        }
      },
      storeArticle() {
        this.cover = this.$refs.coverUpload.getCover();
        let data;
        if(this.cover) {
          this.$compressImage(this.cover).then(res => {
            this.cover = res;
            data = {
              cover: res,
              tag: this.pubTags.join(','),
              type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
              original: this.original === 'origin' ? 1 : 0,
              digest: this.digest
            };
            this.storeArticleWithData(data);
          })
        } else {
          data = {
            tag: this.pubTags.join(','),
            type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
            original: this.original === 'origin' ? 1 : 0,
            digest: this.digest
          };
          this.storeArticleWithData(data);
        }
        this.$refs.storeBtn.disabled = true;
        setTimeout(() => {
          this.$refs.storeBtn.disabled = true;
        }, 1000);
      },

      autoStoreArticleWithData(data) {
        if(this.draftId) {
          data.draft_id = this.draftId;
          this.$parent.updateArticleDraft(data).then(res => {
            if(res.data.success) {
              this.$alert("保存成功");
            } else {
              this.$alert({
                type: 'error',
                content: '保存失败'
              });
            }
          }).catch(error => {
            this.$alert({
              type: 'error',
              content: '保存失败'
            });
          });
        } else {
          this.$parent.storeArticle(data).then(res => {
            if(res.data.success) {
              this.$alert("保存成功");
              this.$router.push({
                path: this.$route.path,
                query: {
                  draftId: res.data.object
                }
              })
            } else {
              this.$alert({
                type: 'error',
                content: '保存失败'
              });
            }
          }).catch(error => {
            this.$alert({
              type: 'error',
              content: '保存失败'
            });
          });
        }
      },
      autoStoreArticle() {
        this.cover = this.$refs.coverUpload.getCover();
        let data;
        if(this.cover) {
          this.$compressImage(this.cover).then(res => {
            this.cover = res;
            data = {
              cover: res,
              tag: this.pubTags.join(','),
              type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
              original: this.original === 'origin' ? 1 : 0,
              digest: this.digest
            };
            this.autoStoreArticleWithData(data);
          })
        } else {
            data = {
              tag: this.pubTags.join(','),
              type: this.typeNames.filter((e, idx) => this.typeSelect[idx]).join(','),
              original: this.original === 'origin' ? 1 : 0,
              digest: this.digest
            };
            this.autoStoreArticleWithData(data);
        }
      },

      fillDraft(draft) {
        this.$router.push({
          path: this.$route.path,
          query: {
            draftId: draft.id
          }
        });
        this.$refs.coverUpload.fillCoverByUrl(draft.cover);
        this.original = draft.origin ? 'origin' : 'reprint';
        this.digest = draft.digest;
        let typeSelect = new Array(this.typeNames.length);
        this.typeNames.forEach((type, idx) => {
          if(draft.type.includes(type)) typeSelect[idx] = true;
        });
        this.typeSelect = typeSelect;
        this.pubTags = draft.tag;
      },

      clear() {
        this.$refs.coverUpload.clear();
        this.digest = '';
        this.typeSelect.fill(false);
        this.pubTags = [];
        this.original = 'origin';
      }
    },
    mounted() {
      this.typeSelect = new Array(this.typeNames.length).fill(false);
    }
  }
</script>

<style lang="less" scoped>
@w: var(--articleInfosChoiceWidth);

.article-infos-choice-wrapper {
  box-sizing: border-box;
  width: @w;
  background-color: white;
  padding: calc(@w * 0.05) calc(@w * 0.08);
  --w1: calc(@w * 0.15);
  --w2: calc(@w - var(--w1) - @w * 0.16);

  .w1, .w2 {
    float: left;
  }

  .w1 {
    width: var(--w1);
  }

  .w2 {
    width: var(--w2);
  }

  .wrapper {
    --lh: calc(@w * 0.03);

    &:not(:first-child) {
      margin-top: calc(@w * 0.04);
    }

    h2 {
      font-size: calc(@w * 0.017);
      line-height: var(--lh);
    }

    &::after {
      content: "";
      display: block;
      clear: both;
    }
  }

  .digest-wrapper {
    .digest-input {
      --textAreaWidth: var(--w2);
      --textAreaHeight: calc(var(--w2) * 0.2);
    }
  }

  .type-wrapper > .type-list {
    --typeListWidth: var(--w2);
    --typeListLineHeight: var(--lh);
  }

  .tag-wrapper > .tag-list {
    --tagListWidth: var(--w2);
    --tagListLineHeight: var(--lh);
  }

  .cover-wrapper > .cover-upload {
    --coverUploadWidth: var(--w2);
    --coverUploadLineHeight: var(--lh);
  }

  .original-wrapper {
    .w2 {
      line-height: var(--lh);

      input:not(:first-child) {
        margin-left: calc(var(--lh) * 2);
      }

      label {
        margin-left: calc(var(--lh) * 0.5);
      }
    }
  }

  .submit-wrapper {
    margin-top: calc(@w * 0.01);
    text-align: right;

    .submit,
    .store {
      padding: calc(@w * 0.01) calc(@w * 0.03);
      font-size: calc(@w * 0.02);
      font-weight: bold;
      border-radius: calc(@w * 0.005);
      background-color: var(--bodyBg);
      color: var(--darkBlue);

      &:hover {
        background-image: linear-gradient(-200deg, #fac0e7, #91baff);
        color: white;
      }
    }
  }
}
</style>